import { createStore  } from 'vuex';
import Cookies from 'js-cookie'

export	default createStore({
	state:{
		isCollapse:true,
		currentMenu:null,
		tabsList:[
			{
				path:'/',
				name:'home1',
				label:'首页',
				path:'home1',
			}
		],
		menu:[],
		token:'',
	},
	mutations:{
		updateIsCollapse(state,payload){
      state.isCollapse=!state.isCollapse;
			console.log(payload,"vuex 使用"); //vuex 使用
		},
		selectMenu(state,val){
    //判断
		if(val.name=='home'){
			state.currentMenu = null
		}else{
			state.currentMenu=val;
			let result=state.tabsList.findIndex(item=>item.name==val.name);
			result ==-1 ? state.tabsList.push(val):'';
			console.log(state.tabsList," vuex 使用 state.tabsList");
		}
		},
		closeTab(state,val){
		let res=state.tabsList.findIndex(item=>item.name==val.name);
		state.tabsList.splice(res,1);
		},

   setMenu( state,val){
		state.menu=val;
		//要做一个持久化
		localStorage.setItem('menu',JSON.stringify(val));
   },

	 //添加菜单页面
	 addMenu(state,router){
     if(!localStorage.getItem('menu')){
          return;
      }
			const menu= JSON.parse(localStorage.getItem('menu'));
			state.menu=menu;

			const menuArray=[];
			menu.forEach(item => {
				if(item.children){
					item.children=item.children.map(item=>{
						let url=`../views/${item.url}.vue`;
						item.component=()=>import(url)
						return item;
					})
					menuArray.push(...item.children);
				}else{
					let url=`../views/${item.url}.vue`;
					item.component=()=>import(url);
					menuArray.push(item);
				}
	 }),

			menuArray.forEach(item=>{
			
				router.addRoute('home1',item);
			})
		
	 },

	 //清楚菜单
	 cleanMenu(state){
		state.menu=[];
		localStorage.removeItem("menu");
	 },

	 //token管理 
	 setToken(state,val){
		state.token=val;
		Cookies.set('token',val);
	 },
	 clearToken(state){
		state.token='';
		Cookies.remove('token');
	 },
   getToken(state){
		state.token=state.token||Cookies.get('token');
   },




	}
})